< previous page page_220 next page >

Page 220
10 Print "hello"
20 Goto 10
Line labels in Visual Basic are similar to the line numbers of early BASIC. In Visual Basic, line labels can include text if you want, but each label must be unique. They are followed by a colon (:), as in the following example:
Private Sub Form_Load()
On Error GoTo FileOpenError
    Open "C:\NOFILE.TXT" For Input As #1
    Line Input #1, sData
    Exit Sub

FileOpenError:
    MsgBox "There was a problem opening the file. Call the Help Desk!"
    End

End Sub
In the preceding sample code, if the Open or Line Input statements cause an error, the statements starting at the label FileOpenError are executed, causing the message to be displayed and ending the program.
You should note a few points about the sample code. First, note the location and style of the error handling routine. It is usually placed near the end of the subroutine, with the label not indented to indicate a special section of code. Second, and more important, notice the Exit Sub statement after the Open statement. It is necessary to prevent the error handling routine from executing even when the Open statement is successful.
Controlling Program Flow after an Error
In the preceding code example, you simply end the program if an error occurs. However, you can handle the error in several (better) ways:
Exit the subroutine after informing the user of the error, and allow the program to continue running with limited functionality.
Resume execution with the next statement following the error.
Provide a way for the user to correct the error and retry the offending statement.
You can also have multiple labels within a procedure and set the current error handler multiple times. For example, you can add a line to the code sample after the Open statement that specifies a new label, FileInputError. You can also turn off error handling with the following statement:
On Error Goto 0
The On Error statement goes hand in hand with the Resume statement. For example, this statement causes errors to be ignored and the program to proceed through each line of code anyway:
On Error Resume Next

 
< previous page page_220 next page >